import React, { Component, Fragment } from 'react';
import { Form, Button, message } from 'antd';
import { connect } from 'dva';
import LoginWrapper from './LoginWrapper';

const { GetYCodeFormItem } = LoginWrapper;

@connect(({ loading: { models: { resetPassword } } }) => ({
  loading: !!resetPassword,
}))
class StepSecond extends Component {
  setValidCodeError = (errorMsg, validCode) => {
    const {
      form: { setFields },
    } = this.props;
    setFields({
      validCode: {
        value: validCode,
        errors: [new Error(errorMsg)],
      },
    });
  };
  handleSubmit = e => {
    e.preventDefault();
    const {
      form: { validateFields },
      setStep,
      dispatch,
      information,
    } = this.props;
    validateFields((err, values) => {
      if (!err) {
        // this.setValidCodeError(`${err}`, values.validCode);
        let action, fieldName;

        if (information.type === 'mobile') {
          action = 'resetPassword/setValidMobileCode';
          fieldName = 'mobile';
        }
        if (information.type === 'mail') {
          action = 'resetPassword/setValidMailCode';
          fieldName = 'mail';
        }
        dispatch({
          type: action,
          payload: {
            type: information.type,
            [fieldName]: information.account,
            code: values.code,
          },
        }).then(() => {
          dispatch({
            type: 'resetPassword/saveInformation',
            payload: {
              type: information.type,
              account: information.account,
              code: values.code,
            },
          });
          setStep(2);
        })
        .catch(errMsg => {
          message.error(errMsg);
        });
      }
    });
  };

  render() {
    const { form, information, loading, setStep } = this.props;
    return (
      <Fragment>
        <Form onSubmit={this.handleSubmit} className="step-content-second">
          {/* <AccountFormItem form={form} disabled={true} initialValue={account} /> */}
          <GetYCodeFormItem
            form={form}
            id="code"
            type={information.type}
            account={information.account}
            disabled={loading}
          />
          <Button onClick={() => setStep(0)}>上一步</Button>
          <Button htmlType="submit" type="primary" style={{ marginLeft: 10 }} loading={loading}>
            下一步
          </Button>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create()(StepSecond);
